package com.spit.fammo.ui.act

import android.os.Bundle
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.spit.amoeba.base.BaseActivity
import com.spit.hkpost.bean.db.ConfigBean
import com.spit.fammo.databinding.ASplashBinding
import com.spit.fammo.api.UIHelper
import com.spit.fammo.bean.AppRoomDataBase
import com.spit.fammo.util.CacheUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel

/**
 * Created by Android Studio.
 * User: ${edison}
 * Date: 2019/9/22
 * Time: 18:11 启动页
 */
class SplashAct : BaseActivity<BaseViewModel, ASplashBinding>(){

    val configDao = AppRoomDataBase.get().getConfigDao()

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.viewModelScope.launch(Dispatchers.IO) {
            var configBean = configDao.findFirst()
            if (configBean == null){
                configBean = ConfigBean()
            }
            configDao.add(configBean)
        }
        setHasPermission()
    }

    private fun setHasPermission() {
        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        setPermissionCancel()
                        return
                    }
                    setPermissionOk()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        ToastUtils.showShort("被永久拒絕授權，請手動授予" +
                                permissions)
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@SplashAct, permissions)
                    } else {
                        ToastUtils.showShort("獲取" + permissions +
                                "失敗")
                    }
                }
            })
    }

    /**
     * 权限有任何一个失败都会走的方法
     */
    fun setPermissionCancel() {
//        act?.finish()
        setHasPermission()
//        showToast("请给需要的权限，以免出现异常")
    }

    /**
     * 权限都成功
     */
    fun setPermissionOk() {
        val user = CacheUtil.getUser()
        if (user != null && user.Password != null){
            UIHelper.startMainAct()
        }else{
            UIHelper.startLoginAct()
        }
        finish()
    }

}